<?php
namespace Home\Service;

class UserService
{
    /**
     * 登录
     * @param  integer $type    1小程序 2公众号 3手机 4其他（邮箱/qq/微博等自行开发）
     * @param  [type]  $data    [description]
     * @return [type]           key 因为所有的项目都是基于接口开发，所以都是返回key
     */
    public function login($type = 1, $data)
    {
        switch ($type) {
            case 1:
                return $this->xcxLogin($data);

            case 2:
                return $this->wxLogin($data);

            default:
                return null;
        }
    }

    /**
     * 小程序登录
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function xcxLogin($data)
    {
        $where = [
            'openid'  => $data['openId'],
            'unionid' => $data['unionid'],
            '_logic_' => 'OR',
        ];

        $is_exists = M('user')->where($where)->count();

        if (!$is_exists) {

            $user_id = $this->register(1, $data);
        } else {

            $user_id = M('user')->where($where)->getField('id');
        }

        // 找不到用户
        if (!$user_id) {
            return false;
        }

        $key = encrypt($user_id);

        S($key, $user_id);

        return $key;
    }

    /**
     * 微信登录
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function wxLogin($data)
    {
        $where = [
            'openid' => $data['openid'],
        ];

        $is_exists = M('user')
            ->where($where)
            ->count();

        if (!$is_exists) {

            $user_id = $this->register(2, $data);
        } else {

            $user_id = M('user')->where($where)->getField('id');
        }

        // 找不到用户
        if (!$user_id) {
            return false;
        }

        session('user_id', $user_id);

        return $user_id;
    }

    /**
     * 注册
     * @param  integer $type [description]
     * @param  [type]  $data [description]
     * @return [type]        [description]
     */
    private function register($type = 1, $data)
    {
        switch ($type) {
            case 1:
                return $this->xcxRegister($data);
                break;

            case 2:
                return $this->wxRegister($data);
                break;

            default:
                # code...
                break;
        }
    }

    /**
     * 小程序注册
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function xcxRegister($user_data)
    {
        $id = 0;
        do {
            $data = [
                'openid'   => $user_data['openId'],
                'username' => $user_data['nickName'],
                'avatar'   => $user_data['avatarUrl'],
                'gender'   => $user_data['gender'],
                'add_time' => CUR_DATETIME,
                // 其他要保存的信息自行添加
            ];
            $id = M('user')->add($data);
        } while (!$id);

        return $id;
    }

    /**
     * 小程序注册
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function wxRegister($user_data)
    {
        $id = 0;
        do {
            $data = [
                'openid'   => $user_data['openid'],
                'nickname' => $user_data['nickname'],
                'headurl'  => $user_data['headimgurl'],
                'gender'   => $user_data['sex'],
                'province' => $user_data['province'],
                'city'     => $user_data['city'],
                'country'  => $user_data['country'],
                'add_time' => CUR_DATETIME,
                // 其他要保存的信息自行添加
            ];
            $id = M('user')->add($data);
        } while (!$id);

        return $id;
    }

    /**
     * 用户余额使用
     * @param  [type] $user_id [description]
     * @param  [type] $money   [description]
     * @param  string $des     [description]
     * @return [type]          [description]
     */
    public function moneyLog($user_id, $money, $des = '')
    {
        $user_money = M('user')->where(['id' => $user_id])->getField('money');

        if ($money < 0 && abs($money) > $user_money) {
            return false;
        }

        // money 可能是负数
        if ($money > 0) {
            $result1 = M('user')->where(['id' => $user_id])->setInc('money', $money);
        } else {
            $result1 = M('user')->where(['id' => $user_id])->setDec('money', abs($money));
        }

        $log = [
            'user_id'     => $user_id,
            'money'       => $money,
            'description' => $des,
            'add_time'    => CUR_DATETIME,
        ];
        $result2 = M('money_log')->add($log);

        return $result1 && $result2;
    }
}
